//
//  HKRequestConfig.m
//  YNDemo
//
//  Created by 胡锦涛 on 2020/11/15.
//

#import "HKRequestConfig.h"
#import "ZBNetworking.h"
#import "HKResponse.h"
#import "HKError.h"
@implementation HKRequestConfig
+(void)setupPublicParameters {
    [HKRequestConfig setupPublicParametersWithBaseServer:SEVER_URL];
}
#pragma mark -- 公共配置 --
+ (void)setupPublicParametersWithBaseServer:(NSString *)baseServer{
    if (!baseServer || [baseServer isEqualToString:@""]) {
        baseServer = SEVER_URL;
    }
    // 公共请求头
    NSMutableDictionary *headers = [NSMutableDictionary dictionary];
    headers[@"authority"] = @"szjw-bss-h5-m1.yunniao.cn";
    headers[@"origin"] = @"https://szjw-bss-h5-m1.yunniao.cn";
    headers[@"sec-fetch-site"] = @"same-origin";
    headers[@"sec-fetch-mode"] = @"cors";
    headers[@"referer"] = @"https://szjw-bss-h5-m1.yunniao.cn/login";
    headers[@"cookie"] = @"developer=qiaoyu";
    [ZBRequestManager setupBaseConfig:^(ZBConfig * _Nullable config) {
        /**
         config.baseServer 设置基础服务器地址
         如果同一个环境，有多个服务器地址，可以在每个请求单独设置 requestr.server  优先级大于config.baseServer
         */
        config.baseServer=baseServer;
        config.headers=headers;//请求头
        config.requestSerializer=ZBJSONRequestSerializer; //全局设置 请求格式 默认JSON
        config.responseSerializer=ZBJSONResponseSerializer; //全局设置 响应格式 默认JSON
        config.timeoutInterval=15;//超时时间  优先级 小于 单个请求重新设置
        //config.retryCount=2;//请求失败 所有请求重新连接次数
        config.consoleLog=YES;//开log
        //请求的信息，可以用来注释和判断使用
        config.userInfo=@{@"info":@"YNNetworking"};
        //添加新的响应数据类型
        //config.responseContentTypes=@[@"text/aaa",@"text/bbb"];
        //内部已存在的响应数据类型
        //@"text/html",@"application/json",@"text/json", @"text/plain",@"text/javascript",@"text/xml",@"image/*",@"multipart/form-data",@"application/octet-stream",@"application/zip"
    }];
    
#pragma mark -- 预处理 请求 --
    [ZBRequestManager setRequestProcessHandler:^(ZBURLRequest * _Nullable request, id  _Nullable __autoreleasing * _Nullable setObject) {
        NSLog(@"请求之前 url:%@",request.url);
        NSArray *tempArray = [request.url componentsSeparatedByString:request.server];
        request.url = [NSString stringWithFormat:@"%@%@%@",request.server,@":8888/mock/139",[tempArray lastObject]];
//        request.url = [NSString stringWithFormat:@"%@%@%@",request.server,@"/api/auth/v1",[tempArray lastObject]];
        NSLog(@"拼接后 url:%@",request.url);
    }];
    
#pragma mark -- 预处理 响应 --
    [ZBRequestManager setResponseProcessHandler:^id(ZBURLRequest * _Nullable request, id  _Nullable responseObject, NSError * _Nullable __autoreleasing * _Nullable error) {
        NSLog(@"成功回调 数据返回之前");
        HKResponse * responseBody = [[HKResponse alloc] init];
        if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
            [responseBody setValuesForKeysWithDictionary:responseObject];
            if ([responseBody.errorCode isEqualToString:@"501"]) {
                //⚠️给*error指针 错误信息，网络请求就会走 失败回调
                *error = [[HKError alloc] initWithErrorType:YNErrorTypeFail errorMessage:@"接口请求成功但服务端返回错误"];
            }else {
                responseObject = responseBody;
            }
            return nil;
        }else {
            //服务端返回格式不正确
            *error = [[HKError alloc] initWithErrorType:YNErrorTypeFail errorMessage:@"服务端返回格式不正确"];
            return nil;
        }
        
    }];
    
#pragma mark -- 预处理 错误 --
    [ZBRequestManager setErrorProcessHandler:^(ZBURLRequest * _Nullable request, NSError * _Nullable error) {
//        if (![YNTool hasNetWork]) {
//            [YNKeyWindow yn_showWithText:@"暂无网络，请稍后重试~"];
//        }
        // HKError 转换
        HKError * ynError = (HKError *)error;
        if (error.code==NSURLErrorCancelled){
            NSLog(@"请求取消❌------------------");
        }else if (error.code==NSURLErrorTimedOut){
            NSLog(@"请求超时");
        }else{
            NSLog(@"请求失败");
        }
        error = (NSError *)ynError;
        
    }];
    
#pragma mark -  证书设置
    //ZBRequestEngine 继承AFHTTPSessionManager，所需其他设置 可以使用[ZBRequestEngine defaultEngine] 自行设置
    NSString *name=@"";
    if (name.length>0) {
        // 先导入证书
        NSString *cerPath = [[NSBundle mainBundle] pathForResource:name ofType:@"cer"];//证书的路径
        NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
        // 如果需要验证自建证书(无效证书)，需要设置为YES，默认为NO;
        securityPolicy.allowInvalidCertificates = YES;
        // 是否需要验证域名，默认为YES;
        securityPolicy.validatesDomainName = NO;
        securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil];
        [ZBRequestEngine defaultEngine].securityPolicy=securityPolicy;
    }
    
}
@end
